using AnalyStock.DataAnalysis;
using AnalyStock.DataManage;

namespace AnalyStock.GrapImage;

/// <summary>
///     股票编码查询面板
/// </summary>
public partial class ChartKline : UserControl
{
    private readonly List<StockName> stockNames = new();

    private void InitializePanel_QueryStockCode()
    {
        QueryCodePanel.Visibility = Visibility.Hidden;
        StockInfosFilled += QueryStockNames_Filled;
        QueryCodePanel.InitializeMouseDarg(this);
    }

   
    private void QueryStockNames_Filled(object sender, IList<StockInfo> stockinfos)
    {        
        if (stockinfos.IsNullOrEmpty())
        {
            return;
        }

        stockNames.AddRange(
            stockinfos.Select(
                item => new StockName(
                    $"{item.Ts_code}/{item.Name}/{CommCNSpell.GetChineseSpell(item.Name)}")));
        TextBoxStockName.TextChanged += TextBoxStockName_TextChanged;
        DGStock.SelectionChanged += StockCode_Changed;
        DGStock.MouseDoubleClick += StockCode_Changed;
    }

    private void BtnQuery_Click(object sender, RoutedEventArgs e)
    {
        //根据查询按钮在屏幕的位置，打开查询窗口
        QueryCodePanel.Visibility = QueryCodePanel.IsVisible
            ? Visibility.Hidden
            : Visibility.Visible;
        if (!QueryCodePanel.IsVisible)
        {
            TextBoxStockName.Text = string.Empty;
        }
    }

    private void StockCode_Changed(object sender, RoutedEventArgs e)
    {
        if (sender is DataGrid { CurrentItem: StockName item })
        {
            ChangeCurrentStock(item.StockCodeName[..9]);
        }
    }

    private void TextBoxStockName_TextChanged(object sender, TextChangedEventArgs e)
    {
        DGStock.ItemsSource = string.IsNullOrEmpty(TextBoxStockName.Text)
            ? default
            : stockNames.Where(n => n.StockCodeName.Contains(TextBoxStockName.Text));
    }

    private record StockName(string StockCodeName);
}